package com.example.netdemo.retrofit;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.logging.Logger;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class HttpLogInterceptor implements Interceptor {
    private static final String TAG = "HttpLogInterceptor";
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Logger.getLogger(TAG).info("----------Request Start----------------");
        //获取请求
        Request request = chain.request();

        //打印请求信息（请求url，请求头，请求体）
        Logger.getLogger(TAG).info("Request Url："+request.url() + "\nMethod:" + request.method() + "\nHeaders:{");

        Headers headers = request.headers();
        for (int i = 0; i < headers.size(); i++) {
            Logger.getLogger(TAG).info(headers.name(i) + ":" + headers.value(i));
        }

        Logger.getLogger(TAG).info("}");

        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Logger.getLogger(TAG).info("Request Body: " + buffer.readUtf8()+"\n");
        }

        //继续执行请求
        Response response = chain.proceed(request);

        String body = response.body().string();
        long duration = response.receivedResponseAtMillis() - response.sentRequestAtMillis();
        int code = response.code();

        Logger.getLogger(TAG).info("\nResponse Body: "+body);

        Logger.getLogger(TAG).info("----------Request End:" + "响应码："+code + "  响应时间："+ duration + "毫秒----------");

        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), body)).build();
    }
}
